package com.itheima.project.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;


@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

        http.formLogin()             //自定义自己编写的登陆页面
                .loginPage("/login.html")    //登录页面设置
                .loginProcessingUrl("/login") //登录访问路径
                .permitAll()//登录页和登录访问路径无需登录（所有用户）也可以访问
                .and()
                .authorizeRequests()
                .antMatchers("/css/**","/images/**").permitAll()
                .antMatchers("/hello/user").hasAnyRole("USER","ADMIN")//角色是USER或ADMIN都可以访问/hello/user
                .antMatchers("/hello/admin").hasRole("ADMIN")//只有ADMIN可以访问/hello/admin
                .anyRequest().authenticated()//其他请求路径只有登录的用户可以访问
                .and()
                .csrf().disable();    //关闭csrf防护（伪造用户意愿的请求）
        return http.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
//        return NoOpPasswordEncoder.getInstance();//生成密码不加密操作对象返回
        return new BCryptPasswordEncoder();
    }

//    @Bean
//    public UserDetailsService userDetailsService() {
//        UserDetails user = User.builder()
//                .username("user")
//                .password("$2a$10$C6Xb8NelcM26kFjpxGrJxOdHtdbLkSAC6QFS/HLlF.p92mc2OgBmW")
//                .roles("USER")
//                .build();
//        UserDetails admin = User.builder()
//                .username("admin")
//                .password("$2a$10$07UN6BiMPmqJF8dXgJ9bX.ozRS7SXwTsZpuaUs5Jz5UdQVyQLGV6C")
//                .roles("USER", "ADMIN")
//                .build();
//        return new InMemoryUserDetailsManager(user, admin);
//    }

}